package com.vnie.mina.client;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.vnie.handler.ClientByteHandler;
import com.vnie.mina.codec.ByteCodecFactory;
import com.vnie.mina.message.BaseMessage;

public class ChinaPayClient {
	
	public ChinaPayClient(String host,int port){
		this.setHOST(host);
		this.setPORT(port);
	}
	
	// 设置报文最大长度
	protected static final int MAX_BUFFER_SIZE = 512;
	//private static String HOST = "60.191.127.165";//"60.191.127.165";
	private String HOST ;

	private int PORT;

	public void send(BaseMessage sendMessage,BaseMessage receiveMessage) {
		// 创建一个非阻塞的客户端程序
		IoConnector  connector = new NioSocketConnector();
		// 设置链接超时时间
		// connector.setConnectTimeout(30000);
		// 添加过滤器
		connector.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new ByteCodecFactory(receiveMessage)));
		// 添加业务逻辑处理器类
		connector.setHandler(new ClientByteHandler());
		IoSession session = null;
		try {
			ConnectFuture future = connector.connect(new InetSocketAddress(
					HOST, PORT));// 创建连接
			future.awaitUninterruptibly();// 等待连接创建完成
			session = future.getSession();// 获得session
			session.write(sendMessage);
			session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
			connector.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getHOST() {
		return HOST;
	}

	public void setHOST(String hOST) {
		HOST = hOST;
	}

	public int getPORT() {
		return PORT;
	}

	public void setPORT(int pORT) {
		PORT = pORT;
	}
	
}
